package com.sharedprint.system.user.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.sharedprint.dics.service.DicsInfoService;
import com.sharedprint.system.area.service.AreaInfoService;
import com.sharedprint.system.organization.service.OrgInfoService;
import com.sharedprint.system.role.service.RoleInfoService;
import com.sharedprint.system.user.pojo.UserInfo;
import com.sharedprint.system.user.service.UserInfoService;
import com.sharedprint.util.Token;

/**
 * 用户管理的Controller
 * 
 * @author Administrator
 *
 */
@Controller
@RequestMapping("/api/userInfo")
public class UserInfoController {
	private static final Logger logger = Logger.getLogger("UserInfoController");
	@Autowired
	private UserInfoService userInfoService;

	@Autowired
	private DicsInfoService dicsInfoService;
	
	@Autowired
	private OrgInfoService orgInfoService;

	@Autowired
	private AreaInfoService areaInfoService;
	
	@Autowired
	private RoleInfoService roleInfoService;
	
	/**
	 * 用户登录
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public Map<String, Object> login(HttpServletRequest request) {
		String userName = request.getParameter("username");
		String passwd = request.getParameter("upwd");

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (userName != null && !"".equals(userName.trim()) && passwd != null && !"".equals(passwd.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("userName", userName);
			searchMap.put("passwd", passwd);
			List<Map<String, Object>> userList = userInfoService.findUserList(searchMap);
			if (userList != null && userList.size() == 1) {
				Map<String, Object> userMap = userList.get(0);
				String token = Token.getTokenString(request.getSession());
				resultMap.put("success", "1");
				resultMap.put("token", token);
				resultMap.put("userId", userMap.get("User_ID"));
				resultMap.put("trueName", userMap.get("trueName"));
				resultMap.put("userName", userMap.get("LoginName"));
			}
		}
		return resultMap;
	}

	/**
	 * 初始用户管理、查询
	 * 
	 * @param req
	 * @return
	 */
	@RequestMapping("/queryPageList")
	@ResponseBody
	public Map<String, Object> queryPageList(HttpServletRequest req) {
		String userName = req.getParameter("queryUserName");
		String queryUserState = req.getParameter("queryUserState");
		String queryUserNameLike = req.getParameter("queryUserNameLike");

		String currentPage = req.getParameter("currentPage");
		String pageSize = req.getParameter("pageSize");
		String excludeUserId = req.getParameter("excludeUserId");

		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		logger.info("token=" + token + ",userId=" + userId);
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		int totalCount = 0;

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			if (currentPage == null || "".equals(currentPage.trim())) {
				currentPage = "0";
			}
			if (pageSize == null || "".equals(pageSize.trim())) {
				pageSize = "10";
			}
			Map<String, Object> searchMap = new HashMap<String, Object>();
			int currentPageIndex = Integer.parseInt(currentPage) * Integer.parseInt(pageSize);
			searchMap.put("currentPageIndex", currentPageIndex);
			searchMap.put("pageSize", Integer.parseInt(pageSize));
			searchMap.put("userName", userName);
			if (queryUserState != "null") {
				searchMap.put("queryUserStatus", queryUserState);
			}
			searchMap.put("queryUserNameLike", queryUserNameLike);

			try {
				totalCount = userInfoService.findCount(searchMap);// 总记录数
				if (totalCount > 0) {
					if (excludeUserId == null || "".equals(excludeUserId.trim())) {
						searchMap.put("excludeUserId", "1");
					}
					userList = userInfoService.findUserList(searchMap);
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		// 获取数据字典
		Map<String, Object> dicsSearchMap = new HashMap<String, Object>();
		List<Map<String, Object>> dicsList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> sexdicsList = new ArrayList<Map<String, Object>>();
		dicsSearchMap.put("dicsCode", "AgeUserStatus");
		dicsList = dicsInfoService.findDicsList(dicsSearchMap);
		dicsSearchMap.put("dicsCode", "Sex");
		sexdicsList = dicsInfoService.findDicsList(dicsSearchMap);
		//获取用户状态
		for (int i = 0; i < userList.size(); i++) {
			for (int j = 0; j < dicsList.size(); j++) {
				if (userList.get(i).get("Status").toString().equals(dicsList.get(j).get("key_value").toString())) {
					userList.get(i).put("AgeUserStatus", dicsList.get(j).get("key_name").toString());
				}
			}
		}
		//获取用户性别
		for (int i = 0; i < userList.size(); i++) {
			for (int j = 0; j < sexdicsList.size(); j++) {
				if (userList.get(i).get("Sex").toString().equals(sexdicsList.get(j).get("key_value").toString())) {
					userList.get(i).put("Sex", sexdicsList.get(j).get("key_name").toString());
				}
			}
		}
		resultMap.put("currentPage", Integer.parseInt(currentPage) + 1);
		resultMap.put("pageTotal", totalCount);
		resultMap.put("pageList", userList);
		resultMap.put("statusList", dicsList);
		resultMap.put("success", "1");
		return resultMap;
	}

	// 初始化前台新增数据
	@RequestMapping("/initAdd")
	@ResponseBody
	public Map<String, Object> initAdd(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");

		System.out.println("token=" + token + ",userId=" + userId);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> dicsList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> dicdList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> orgInfoList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> areaInfoList = new ArrayList<Map<String, Object>>();
		List<Map<String, Object>> roleInfoList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null) {
			// 获取数据字典
			Map<String, Object> dicsSearchMap = new HashMap<String, Object>();
			dicsSearchMap.put("dicsCode", "Sex");
			dicsList = dicsInfoService.findDicsList(dicsSearchMap);
			dicsSearchMap.put("dicsCode", "DefaultPasswd");
			dicdList = dicsInfoService.findDicsList(dicsSearchMap);
            
			//获取机构下拉框
			Map<String, Object> searchMap = new HashMap<String, Object>();
		    orgInfoList = orgInfoService.findOrgInfoList(searchMap);
		    
		   //获取机构下拉框
		    areaInfoList = areaInfoService.findAreaInfoList(searchMap);
		    
		   //获取机构下拉框
		    roleInfoList = roleInfoService.findRoleInfoList(searchMap);
		}
		resultMap.put("dicsList", dicsList);
		resultMap.put("dicdList", dicdList);
		resultMap.put("orgInfoList", orgInfoList);
		resultMap.put("areaInfoList", areaInfoList);
		resultMap.put("roleInfoList", roleInfoList);
		resultMap.put("success", "1");
		return resultMap;

	}
	/**
	 * 验证用户名称
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/validLoginName")
	@ResponseBody
	public boolean validLoginName(HttpServletRequest req){
		String userName = req.getParameter("addUserName");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		logger.info("token=" + token + ",userId=" + userId + ",userName=" + userName);
		boolean result = false;
		if (userName != null && !"".equals(userName.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("userName", userName);
			int count = userInfoService.findCount(searchMap);
			if (count == 0) {
				result = true;
			}
		}
		return result;
	}

	/**
	 * 保存用户信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/add")
	@ResponseBody
	public Map<String, Object> add(HttpServletRequest req) {
		String addTrueName = req.getParameter("addTrueName");
		String addUserName = req.getParameter("addUserName");
		String addUserOrp = req.getParameter("addUserOrp");
		String addUserArea = req.getParameter("addUserArea");
		String addUserSex = req.getParameter("addUserSex");
		String addUserMobile = req.getParameter("addUserMobile");
		String addUserEmail = req.getParameter("addUserEmail");
		String addUserQQ = req.getParameter("addUserQQ");
		String addUserWeixin = req.getParameter("addUserWeixin");
		String addUserAddress = req.getParameter("addUserAddress");

		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (addTrueName != null && !"".equals(addTrueName.trim()) && addUserName != null
				&& !"".equals(addUserName.trim()) &&  token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim())) {
			
			UserInfo userInfo = new UserInfo();
			userInfo.setTruename(addTrueName);
			userInfo.setLoginname(addUserName);
			userInfo.setOrgCode(addUserOrp);
			userInfo.setAreaCode(addUserArea);
			//userInfo.setPasswd(dicdList);
			userInfo.setAddress(addUserAddress);
			userInfo.setEmail(addUserEmail);
			userInfo.setMobile(addUserMobile);
			userInfo.setSex(addUserSex);
			userInfo.setQq(addUserQQ);
			userInfo.setWeixin(addUserWeixin);
			try {
				int success = userInfoService.saveInfo(userInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "保存失败");
				}
			} catch (Exception e) {
				logger.info("保存异常=" + e.getMessage());
				e.printStackTrace();
				resultMap.put("msg", "保存异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 获取修改相关信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/initUpdate")
	@ResponseBody
	public Map<String, Object> initUpdate(HttpServletRequest req) {
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		String updateUserId = req.getParameter("updateUserId");
		logger.info("token=" + token + ",userId=" + userId + ",updateUserId=" + updateUserId);

		Map<String, Object> userMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim()) && userId != null
				&& !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("updateUserId", updateUserId);
			userList = userInfoService.findPageList(searchMap);
			userMap = userList.get(0);
			userList = userInfoService.findPageList(null);
		}
		resultMap.put("userList", userList);
		resultMap.put("userMap", userMap);
		resultMap.put("success", "1");
		return resultMap;
	}

	/**
	 * 修改信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/update")
	@ResponseBody
	public Map<String, Object> update(HttpServletRequest req) {
		String updateUserName = req.getParameter("updateUserName");
		String updateTrueName = req.getParameter("updateTrueName");
		String updateUserPasswd = req.getParameter("updateUserPasswd");
		String updateUserId = req.getParameter("updateUserId");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");

		if (updateUserName != null && !"".equals(updateUserName.trim()) && updateTrueName != null
				&& !"".equals(updateTrueName.trim()) && updateUserPasswd != null
				&& !"".equals(updateUserPasswd.trim())) {
			UserInfo userInfo = new UserInfo();
			userInfo.setLoginname(updateUserName);
			userInfo.setTruename(updateTrueName);
			userInfo.setPasswd(updateUserPasswd);
			userInfo.setUserId(Integer.parseInt(updateUserId));
			try {
				int success = userInfoService.updateInfo(userInfo);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "修改失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("修改异常=" + e.getMessage());
				resultMap.put("msg", "修改异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 删除信息
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/delete")
	@ResponseBody
	public Map<String, Object> delete(HttpServletRequest req) {
		String deleteUserId = req.getParameter("deleteUserId");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		logger.info("token=" + token + ",userId=" + userId + ",deleteUserId=" + deleteUserId);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (deleteUserId != null && !"".equals(deleteUserId.trim()) && token != null && !"".equals(token.trim())
				&& userId != null && !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("deleteUserId", deleteUserId);
			try {
				int success = userInfoService.deleteInfo(searchMap);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "删除失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("删除异常=" + e.getMessage());
				resultMap.put("msg", "删除异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}

	/**
	 * 获取详情
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 * @throws ServletException
	 */
	@RequestMapping("/detail")
	@ResponseBody
	public Map<String, Object> detail(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String token = req.getHeader("token");
		String userId = req.getParameter("userId");
		logger.info("token=" + token + ",userId=" + userId + ",userId=" + userId);

		Map<String, Object> userMap = new HashMap<String, Object>();
		Map<String, Object> resultMap = new HashMap<String, Object>();
		List<Map<String, Object>> userList = new ArrayList<Map<String, Object>>();
		if (token != null && !"".equals(token.trim()) && userId != null && !"".equals(userId.trim()) && userId != null
				&& !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("userId", userId);
			userList = userInfoService.findPageList(searchMap);
			userMap = userList.get(0);
		}
		resultMap.put("userMap", userMap);
		resultMap.put("success", "1");
		return resultMap;
	}
	
	/**
	 * 重置密码
	 * 
	 * @param req
	 * @param resp
	 * @throws IOException
	 */
	@RequestMapping("/resetPwd")
	@ResponseBody
	public Map<String, Object> resetPwd(HttpServletRequest req) {
		String resetUserId = req.getParameter("resetUserId");
		String token = req.getHeader("token");
		String userId = req.getHeader("userId");
		logger.info("token=" + token + ",userId=" + userId + ",resetUserId=" + resetUserId);

		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap.put("success", "0");
		if (resetUserId != null && !"".equals(resetUserId.trim()) && token != null && !"".equals(token.trim())
				&& userId != null && !"".equals(userId.trim())) {
			Map<String, Object> searchMap = new HashMap<String, Object>();
			searchMap.put("resetUserId", resetUserId);
			try {
				int success = userInfoService.resetInfo(searchMap);
				if (success > 0) {
					resultMap.put("success", "1");
				} else {
					resultMap.put("msg", "重置失败");
				}
			} catch (Exception e) {
				e.printStackTrace();
				logger.info("重置异常=" + e.getMessage());
				resultMap.put("msg", "重置异常");
			}
		} else {
			resultMap.put("msg", "请上传相关参数");
		}
		return resultMap;
	}
}
